//
//  UserAccount.swift
//  Status
//
//  Created by 花轮 on 15/5/13.
//  Copyright (c) 2015年 花轮. All rights reserved.
//

import UIKit

class UserAccount: NSObject, Printable,NSCoding {
    
    let access_token: String
    let expires_in: NSTimeInterval
    let uid: String
    let expireDate: NSDate
    
    var name: String?
    var avatar_large: String?
    
    let  KAccess_token = "access_token"
    let KExpires_in = "expires_in"
    let KUid = "uid"
    let KExpireDate = "expireDate"
    let KName = "name"
    let KAvatar_large = "avatar_large"
    
    init(dict: [String: AnyObject])
    {
        access_token = dict[KAccess_token] as! String
        expires_in = dict[KExpires_in] as! NSTimeInterval
        uid = dict[KUid] as! String
        expireDate = NSDate(timeIntervalSinceNow: expires_in)
    }
    
    
    // 目前为止，在swi中，不允许定义 class 的存储型常量，需要使用 static
    static let accountPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! String).stringByAppendingPathComponent("account.plist")
    
    class func loadAccessToken(params:[String: String], completion:(account: UserAccount?)->())
    {
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        
        NetworkTools.requestJSON(.POST, URLStr: urlStr, parameters: params) { (JSON) -> () in
            if JSON == nil
            {
                completion(account: nil)
                return
            }
            
            let account = UserAccount(dict: JSON as! [String: AnyObject])
            
            account.loadUserInfo(completion)
        }
    }
    
    // 加载用户信息
    func loadUserInfo(completion:(account: UserAccount?)->())
    {
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        let params = [KAccess_token:access_token, KUid:uid];
        
        NetworkTools.requestJSON(.GET, URLStr: urlStr, parameters: params) { (abc) -> () in
//             错误处理
                        if abc == nil
                        {
                            completion(account: nil)
                            return
                        }
            
                        // 给对象设置属性
                        if let dict = abc as? [String: AnyObject]
                        {
                            self.name = dict["name"] as? String
                            self.avatar_large = dict["avatar_large"] as? String
            
            //                println(self)
            
                            // 归档保存数据
                            NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
            
                            completion(account: self)
                        }
                        else
                        {
                            // 能够执行到此，网络回调的 error == nil
                            let jsonError = NSError(domain: "微博", code: -2, userInfo: ["error":"数据解析错误"])
                            completion(account: nil)
                        }

        }
        
    }
    
    // 从本地沙盒读取用户数据(解档)
    class func loadUserAccount() -> UserAccount? {
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.accountPath) as? UserAccount
        {
            // 考虑到一个细节 - 过期日期，一旦过期，需要用户重新登录
            if account.expireDate.compare(NSDate()) == NSComparisonResult.OrderedDescending
            {
                return account;
            }
        }
        return nil
    }
    
    // 重写对象的描述信息 - 建议重要的模型类，最好添加一个 方便调试
    override var description: String{
        let properties = [KAccess_token, KExpires_in, KUid, KExpireDate, KName, KAvatar_large];
        
        // 模型转字典
        return "\(dictionaryWithValuesForKeys(properties))"
    }
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey:KAccess_token)
        aCoder.encodeDouble(expires_in, forKey: KExpires_in)
        aCoder.encodeObject(expireDate, forKey: KExpireDate)
        aCoder.encodeObject(uid, forKey: KUid)
        aCoder.encodeObject(name, forKey: KName)
        aCoder.encodeObject(avatar_large, forKey: KAvatar_large)
    }
    
    required init(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey(KAccess_token) as! String
        expires_in = aDecoder.decodeDoubleForKey(KExpires_in) as NSTimeInterval
        expireDate = aDecoder.decodeObjectForKey(KExpireDate) as! NSDate
        uid = aDecoder.decodeObjectForKey(KUid) as! String
        name = aDecoder.decodeObjectForKey(KName) as? String
        avatar_large = aDecoder.decodeObjectForKey(KAvatar_large) as? String
    }
}
